import '../../public.dart';
// import 'package:url_launcher/url_launcher.dart';
import 'model.dart';
import 'home_actions.dart';
import 'home_title.dart';
import 'home_carousel.dart';
import 'home_card_item.dart';

/// 主页面状态管理
class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomePageState();
}

class _HomePageState extends State<HomeScreen>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return ProviderWidget<HomeModel>(
      onModelReady: (model) => model.init(),
      builder: (context, model, child) {
        return Scaffold(
          backgroundColor: Colors.white,
          body: _buildContent(context, model, child),
        );
      },
      model: Provider.of<HomeModel>(context),
    );
  }

  /// 构建主内容区域
  Widget _buildContent(BuildContext context, HomeModel model, Widget? child) {
    if (model.busy) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(),
            SizedBox(height: 12),
            Text('loading...'),
          ],
        ),
      );
    }

    // 如果分类数据还没加载，显示空白
    if (model.categories.isEmpty) {
      return const Center(child: Text('The category is empty'));
    }

    return SafeArea(
      child: DefaultTabController(
        length: model.categories.length,
        child: Builder(
          builder: (context) {
            // 方案1: 使用 TabBarView 的监听
            return NestedScrollView(
              headerSliverBuilder: (context, innerBoxIsScrolled) => [
                // 顶部区域 - 不吸顶
                const SliverToBoxAdapter(child: HomeTitle()),
                SliverToBoxAdapter(child: HomeCarousel(list: model.bannerList)),
                const SliverToBoxAdapter(child: HomeActions()),
                const SliverToBoxAdapter(child: SizedBox(height: 12)),
                // 吸顶的 TabBar
                SliverPersistentHeader(
                  pinned: true,
                  delegate: _StickyTabBarDelegate(
                    tabs: model.categories
                        .map((e) => Tab(text: e.typeName))
                        .toList(),
                    // 方案2: 传递点击回调
                    onTabChanged: (index) => _handleTabChanged(index, model),
                  ),
                ),
              ],
              body: _buildTabBarViewWithListener(model),
            );
          },
        ),
      ),
    );
  }

  /// 构建带监听的 TabBarView
  Widget _buildTabBarViewWithListener(HomeModel model) {
    final categories = model.categories;

    return Builder(
      builder: (context) {
        // 获取 TabController
        final tabController = DefaultTabController.of(context);

        // 监听滑动和点击
        tabController.addListener(() {
          if (!tabController.indexIsChanging) {
            _handleTabChanged(tabController.index, model);
          }
        });

        return TabBarView(
          children: categories.map((category) {
            final categoryId = category.id?.toString() ?? '';
            final categoryItems = model.categoryItems[categoryId];

            if (categoryItems?.isLoading == true) {
              return const Center(child: CircularProgressIndicator());
            }

            if (categoryItems?.list.isEmpty == true &&
                categoryItems?.inted == true) {
              return const Center(child: Text('no data'));
            }

            return _buildTabList(categoryItems!);
          }).toList(),
        );
      },
    );
  }

  /// 处理 tab 切换（支持点击和滑动）
  void _handleTabChanged(int index, HomeModel model) {
    if (index >= 0 && index < model.categories.length) {
      final category = model.categories[index];
      final categoryId = category.id?.toString() ?? '';
      // 1. 重新加载该分类的数据（如果为空）
      if (model.categoryItems[categoryId]?.list.isEmpty ?? true) {
        model.loadCategoryItems(category);
      }
    }
  }

  /// 构建单个 Tab 的内容列表
  Widget _buildTabList(CategoryItems item) {
    return MediaQuery.removePadding(
      context: context,
      removeTop: true,
      child: ListView.builder(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        itemCount: item.list.length,
        itemBuilder: (context, index) {
          return HomeCardItem(item: item.list[index], type: item.type);
        },
      ),
    );
  }
}

/// 吸顶 TabBar 代理
class _StickyTabBarDelegate extends SliverPersistentHeaderDelegate {
  const _StickyTabBarDelegate({required this.tabs, this.onTabChanged});

  final List<Tab> tabs;
  final Function(int)? onTabChanged;

  @override
  double get minExtent => 48;

  @override
  double get maxExtent => 48;

  @override
  Widget build(
    BuildContext context,
    double shrinkOffset,
    bool overlapsContent,
  ) {
    return Container(
      color: Colors.white, // 动态透明度
      child: TabBar(
        indicatorColor: Colors.transparent,
        labelColor: Colors.blue,
        unselectedLabelColor: Colors.grey,
        dividerColor: Colors.transparent,
        isScrollable: true,
        tabAlignment: TabAlignment.start,
        // 移除 TabBar 自身的内边距
        padding: EdgeInsets.only(left: 15),
        // 使用 labelPadding 控制每个 Tab 的内边距
        labelPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 2),
        labelStyle: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
        tabs: tabs,
        onTap: (index) {
          // 点击事件回调
          if (onTabChanged != null) {
            onTabChanged!(index);
          }
        },
      ),
    );
  }

  @override
  bool shouldRebuild(covariant _StickyTabBarDelegate oldDelegate) {
    return oldDelegate.tabs != tabs || oldDelegate.onTabChanged != onTabChanged;
  }
}
